import type { FormProps } from 'antd'
import { Button, Form, Input } from 'antd'
import { useEffect, useRef, useState } from 'react'
import Store from '../../store'
import { useNavigate } from 'react-router-dom'
type FieldType = {
    username?: string
    password?: string
    captcha?: string
}
function Box() {
    const [captcha, setCaptcha] = useState('')
    const [form] = Form.useForm<FieldType>()
    const toLogin = Store((state) => state.toLogin)
    const getCaptcha = Store((state) => state.getCaptcha)
    const navigate = useNavigate()
    const captchaInputRef = useRef<any>(null)
    useEffect(() => {
        // 已登录则跳转首页
        if (localStorage.getItem('authToken')) {
            navigate('/')
            return
        }
        handleGetCaptcha()
    }, [])
    const handleGetCaptcha = () => {
        getCaptcha()
            .then((res: string) => {
                setCaptcha(res)
                // 验证码自动固定光标
                setTimeout(() => {
                    captchaInputRef.current?.focus()
                }, 0)
            })
            .catch(() => {
                setCaptcha('')
            })
    }
    const onFinish: FormProps<FieldType>['onFinish'] = (values) => {
        toLogin(values)
            .then((res: string) => {
                if (res) {
                    // 登录返回的路由列表的第一个路径
                    navigate('/')
                }
            })
            .catch((err) => {
                setCaptcha('')
                // 清空验证码输入框
                form.resetFields(['captcha'])
                handleGetCaptcha()
            })
    }

    const onFinishFailed: FormProps<FieldType>['onFinishFailed'] = (
        errorInfo
    ) => {
        console.log('Failed:', errorInfo)
    }
    return (
        <Form
            form={form}
            name="basic"
            labelCol={{ span: 6 }}
            wrapperCol={{ span: 18 }}
            style={{ maxWidth: 600 }}
            onFinish={onFinish}
            onFinishFailed={onFinishFailed}
            autoComplete="off"
            initialValues={{ username: 'admin', password: '123456', captcha: '' }}
        >
            <Form.Item<FieldType>
                label="用户名"
                name="username"
                rules={[
                    {
                        required: true,
                        message: '请输入用户名!',
                    },
                ]}
            >
                <Input />
            </Form.Item>

            <Form.Item<FieldType>
                label="密码"
                name="password"
                rules={[
                    {
                        required: true,
                        message: '请输入密码!',
                    },
                ]}
            >
                <Input.Password />
            </Form.Item>
            <Form.Item label="验证码">
                <div className="flex">
                    <Form.Item<FieldType>
                        name="captcha"
                        noStyle
                        rules={[
                            {
                                required: true,
                                message: '请输入验证码!',
                            },
                        ]}
                    >
                        <Input style={{ width: '60%' }} ref={captchaInputRef} />
                    </Form.Item>
                    {captcha && (
                        <span
                            style={{
                                marginLeft: '10px',
                                cursor: 'pointer',
                                height: '32px',
                                display: 'inline-block',
                            }}
                            onClick={handleGetCaptcha}
                            dangerouslySetInnerHTML={{ __html: captcha }}
                        />
                    )}
                </div>
            </Form.Item>
            <Form.Item label={null}>
                <Button type="primary" htmlType="submit">
                    登录
                </Button>
            </Form.Item>
        </Form>
    )
}
export default Box
